package com.miyuan.view.machine;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.miyuan.R;
import com.miyuan.base.BaseFragment;
import com.miyuan.bean.RequestBean;
import com.miyuan.bean.ResultBean;
import com.miyuan.bean.request.MachineGoodsParam;
import com.miyuan.bean.request.MachineListParam;
import com.miyuan.bean.respone.CategoryListBean;
import com.miyuan.bean.respone.GoodsListBean;
import com.miyuan.bean.respone.MachineGoodsBean;
import com.miyuan.bean.respone.MachineListBean;
import com.miyuan.net.NetService;
import com.miyuan.net.RetrofitClient;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.ex.loadmore.SimpleLoadMoreViewCreator;
import net.idik.lib.slimadapter.ex.loadmore.SlimMoreLoader;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//售货机商品列表页面

public class MachineGoodsListFragment extends BaseFragment {

    MachineInfosFragment machineInfosFragment;
    public SlimAdapter categorySlimAdapter;
    @BindView(R.id.goods_list)
    RecyclerView recyclerView;
    @BindView(R.id.category_list)
    RecyclerView categoryList;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefreshLayout;

    public String classificationId = "";
    private int current = 1;
    private int size = 200;
    private boolean hasMore = true;
    SlimAdapter slimAdapter;

    public static MachineGoodsListFragment newInstance(String vendorId, String controlNumber) {
        MachineGoodsListFragment scanFragment = new MachineGoodsListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("vendorId", vendorId);
        bundle.putString("controlNumber", controlNumber);
        scanFragment.setArguments(bundle);
        return scanFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setFragmentLayout(R.layout.fragment_machine_goods);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        title.setText("工控号" + getArguments().getString("controlNumber"));
        RetrofitClient.getInstance()
                .create(NetService.class)
                .getGoodsCategory(new RequestBean().toRequestBody())
                .enqueue(new Callback<ResultBean<List<CategoryListBean>>>() {

                    @Override
                    public void onResponse(Call<ResultBean<List<CategoryListBean>>> call, Response<ResultBean<List<CategoryListBean>>> response) {
                        ResultBean<List<CategoryListBean>> resultBean = response.body();
                        if (resultBean.getData() != null) {
                            if (resultBean.getData().size() > 0) {
                                classificationId = resultBean.getData().get(0).getId();
                            } else {
                                classificationId = "";
                            }
                            initCategoryList(resultBean.getData());
                            initGoodsList(new ArrayList());
                            requestGoodsList(classificationId);
                        } else {
                            Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultBean<List<CategoryListBean>>> call, Throwable t) {
                    }
                });
    }

    public void requestGoodsList(String classificationId) {
        String vendorId = getArguments().getString("vendorId");
        if (vendorId != null) {
            RetrofitClient.getInstance()
                    .create(NetService.class)
                    .getMachineGoods(vendorId, new MachineGoodsParam(classificationId, current, size).toRequestBody())
                    .enqueue(new Callback<ResultBean<MachineGoodsBean>>() {

                        @Override
                        public void onResponse(Call<ResultBean<MachineGoodsBean>> call, Response<ResultBean<MachineGoodsBean>> response) {
                            if (swipeRefreshLayout != null) {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                            ResultBean<MachineGoodsBean> resultBean = response.body();
                            if (resultBean.getData() != null) {
                                slimAdapter.updateData(resultBean.getData().getRecords());
                                int listSize = resultBean.getData().getRecords().size();
                                hasMore = listSize >= size;
                            } else {
                                Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultBean<MachineGoodsBean>> call, Throwable t) {
                            if (swipeRefreshLayout != null) {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }
                    });
        }
    }

    public void initCategoryList(List list) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        categoryList.setLayoutManager(linearLayoutManager);
        categorySlimAdapter = SlimAdapter.create().register(R.layout.item_category_list, new SlimInjector<CategoryListBean>() {
            @Override
            public void onInject(final CategoryListBean data, IViewInjector injector) {
                injector.text(R.id.category_name, data.getName());
                TextView selectLine = (TextView) injector.findViewById(R.id.select_line);
                if (classificationId.equals(data.getId())) {
                    selectLine.setVisibility(View.VISIBLE);
                } else {
                    selectLine.setVisibility(View.INVISIBLE);
                }

                injector.clicked(R.id.category_item, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        classificationId = data.getId();
                        current = 1;
                        requestGoodsList(classificationId);
                        categorySlimAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).attachTo(categoryList);
        categorySlimAdapter.updateData(list);
    }

    public void initGoodsList(List list) {
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
//        recyclerView.setLayoutManager(gridLayoutManager);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        slimAdapter = SlimAdapter.create().register(R.layout.item_goods_list, new SlimInjector<MachineGoodsBean.RecordsBean>() {
            @Override
            public void onInject(MachineGoodsBean.RecordsBean data, IViewInjector injector) {
                injector.text(R.id.goods_name, data.getName().trim());
//                injector.text(R.id.stock, "货存" + data.getInventory());
                injector.text(R.id.passagewayNumber, "货道号" + data.getPassagewayNumber());
                injector.text(R.id.sold, data.getSold() + "");
                if (data.getPicture() != null) {
                    ImageView img = (ImageView) injector.findViewById(R.id.goods_img);
                    Glide.with(getActivity())
                            .load(data.getPicture())
                            .into(img);
                } else {
                    injector.image(R.id.goods_img, R.mipmap.machine_default);
                }
            }
        }).enableLoadMore(new SlimMoreLoader(getActivity(), new SimpleLoadMoreViewCreator(getActivity()).setNoMoreHint("").setLoadingHint("").setPullToLoadMoreHint("")) {
            @Override
            protected void onLoadMore(final Handler handler) {
                ++current;
                String vendorId = getArguments().getString("vendorId");
                RetrofitClient.getInstance()
                        .create(NetService.class)
                        .getMachineGoods(vendorId, new MachineGoodsParam(classificationId, current, size).toRequestBody())
                        .enqueue(new Callback<ResultBean<MachineGoodsBean>>() {

                            @Override
                            public void onResponse(Call<ResultBean<MachineGoodsBean>> call, Response<ResultBean<MachineGoodsBean>> response) {
                                if (swipeRefreshLayout != null) {
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                                ResultBean<MachineGoodsBean> resultBean = response.body();
                                if (resultBean.getData() != null) {
                                    handler.loadCompleted(resultBean.getData().getRecords());
                                    int listSize = resultBean.getData().getRecords().size();
                                    hasMore = listSize >= size;
                                } else {
                                    Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResultBean<MachineGoodsBean>> call, Throwable t) {
                                if (swipeRefreshLayout != null) {
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                            }
                        });
            }

            @Override
            protected boolean hasMore() {
                return hasMore;
            }
        }).attachTo(recyclerView);
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                current = 1;
                requestGoodsList(classificationId);
            }
        });
        slimAdapter.updateData(list);
    }

    @OnClick(R.id.back_layout)
    void back() {
        getActivity().finish();
    }

    @OnClick(R.id.show_content)
    void show() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        machineInfosFragment = MachineInfosFragment.newInstance(getArguments());
        transaction.replace(R.id.root_fragment, machineInfosFragment);
        transaction.addToBackStack("machineInfosFragment");
        transaction.commit();
    }
}
